
import { Toast } from 'vant'
import { VanToast } from 'vant/types/toast'
import { isAndroid, parseQuery, isUndefined } from './utils'
// fromApp
// 会考吧：HuiKaoBa
// 我的网校：MyOnlineSchool
// 百龙教育：BaiLongSchool
// 123医学考试网：YiKaoSchool
// 华信医考：HuaXinSchool\
export const AppInfo = {
  isApp: isAndroid ? !!parseQuery().fromApp : !isUndefined(window.webkit) && !!parseQuery().fromApp,
  // isApp: isAndroid ? true : !isUndefined(window.webkit),
  appName: '',
  /**
   * 调用app方法
   * @param methodName showLoading：显示 “加载中…”，hideLoading隐藏 “加载中…”，reLogin：重新登录相关
   * goBack：退出webview，goShare：分享，getUserData：获取用户信息
   * @param content 发送参数
   * @param hasCallback 是否有回调方法
   */
  callMethod (methodName: string, content?: any, hasCallback = false) {
    if (!this.isApp) {
      if (methodName === 'goBack') {
        history.back()
      }
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.resolve('notApp')
    }
    const argString = content
      ? typeof content === 'object' ? JSON.stringify(content) : content
      : content
    const callPromise = new Promise((resolve, reject) => {
      if (hasCallback) {
        // @ts-ignore
        window[methodName + 'Callback'] = (data: any) => {
          if (isAndroid && data) {
            resolve(JSON.parse(data))
          } else {
            resolve(data)
          }
        }
      } else {
        resolve('')
      }
    })
    if (isAndroid) {
      /* eslint-disable */
      // @ts-ignore
      window.WebViewJavascriptBridge.callHandler(methodName, content, window[methodName + 'Callback'])
    } else {
      window.webkit.messageHandlers[methodName].postMessage({ body: argString || '' })
    }
    return callPromise
  },
}

export function connectWebViewJavascriptBridge(callback: any) {
  if (window.WebViewJavascriptBridge) {
    AppInfo.isApp = true
    callback(window.WebViewJavascriptBridge)
  } else {
    document.addEventListener(
      'WebViewJavascriptBridgeReady'
      , function () {
        AppInfo.isApp = true
        callback(window.WebViewJavascriptBridge)
      },
      false
    );
  }
}

export const loading = (function () {
  let loadingInstace: VanToast
  let instanceNum = 0
  const show = (message = '', place: string = '') => {
    instanceNum++
    console.log(place, '===show===', instanceNum)
    if (loadingInstace) {
      return
    }
    loadingInstace = Toast({
      type: 'loading',
      mask: true,
      loadingType: 'spinner',
      message,
      duration: 0,
    })
  }
  const hide = (place: string = '') => {
    // console.log('will hide', instanceNum)
    if (instanceNum === 0) {
      return
    }
    // setTimeout(() => {
      console.log(place, '===hide===', instanceNum)
      instanceNum--
      if (instanceNum <= 0) {
        clear()
      }
    // }, 1)
  }
  const clear = () => {
    instanceNum = 0
    loadingInstace && loadingInstace.clear()
    loadingInstace = null as any
  }
  return { show, hide, clear }
})()
